from re import findall
from lxml import etree


class Parser:
    def __init__(self):
        pass

    def parse_by_xpath(self, data, path, mode="fuse"):
        if data is None:
            return None
        if type(data) == str:
            data = etree.HTML(data)
        assert type(data) == etree._Element, "input data type is {0}!".format(type(data))
        assert mode in ["get", "list", "fuse"], "check the mode, current mode is {0}".format(mode)
        ret_datas = data.xpath(path)
        if len(ret_datas) > 0:
            if mode == "list":
                return [etree.tostring(r_data, encoding="utf-8").decode("utf-8").strip() for r_data in ret_datas]
            if mode == "get":
                return etree.tostring(ret_datas[0], encoding="utf-8").decode("utf-8").strip()
            if mode == "fuse":
                return "\n".join(
                    [etree.tostring(r_data, encoding="utf-8").decode("utf-8").strip() for r_data in ret_datas])
            raise Exception("mode error")
        return [] if mode == "list" else None

    def parse_by_regex(self, data, pattern, mode="fuse"):
        if data is None:
            return None
        if type(data) == etree._Element:
            data = etree.tostring(data, encoding="utf-8").decode("utf-8")
        assert type(data) == str, "input data type is {0}".format(type(data))
        assert mode in ["get", "list", "fuse"], "check the mode, current mode is {0}".format(mode)
        ret_datas = findall(pattern, data)
        if len(ret_datas) > 0:
            if mode == "list":
                return [r_data.strip() for r_data in ret_datas]
            r_data = ret_datas[0] if mode == "get" else "\n".join(ret_datas)
            return r_data.strip()
        return [] if mode == "list" else None


if __name__ == '__main__':
    parser = Parser()
